/**
 * @author:linjiye
 * @date: 2025/1/9
 * @desc:
 **/

import {
    ImageBackground,
    Pressable,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    Image,
    KeyboardAvoidingView, Platform, TouchableWithoutFeedback, Keyboard, Button, Modal
} from 'react-native'
import React, {useCallback, useEffect, useState} from 'react'
import {StatusBar} from "expo-status-bar";
import Animated, {FadeInDown, FadeInLeft, FadeInRight, FadeInUp} from "react-native-reanimated";
import {Colors} from "@/constants/Colors";
import {router} from "expo-router";
import FcTextInput from "@/components/FcTextInput";
import {LinearGradient} from "expo-linear-gradient";
import {useGetRandomImageQuery,useLoginMutation, useGetUserInfoMutation} from "@/store/api/login/loginApi";
import uri from "ajv/lib/runtime/uri";
import FcButton from "@/components/FcButton";
import {Toast} from "@ant-design/react-native";
import {useDispatch} from "react-redux";
import {set_loginData, set_token, set_userInfo} from "@/store/reducer/login/loginSlice";
// import * as WeChat from 'expo-wechat';
import LoginTest from "@/app/login/LoginTest";
import * as WebBrowser from "expo-web-browser";
import WechatLogin from "@/app/login/WechatLogin";

type Props = {}

const index = (props: Props) => {
    const [codeImg, setCodeImg] = useState('')
    const [userName, setUserName] = useState('')
    const [userPassword, setUserPassword] = useState('')
    const [code, setCode] = useState('')
    const [remember, setRemember] = useState(false)
    const [agreement, setAgreement] = useState(false)
    const [isShow, setIsShow] = useState(false)

    const dispatch = useDispatch();

    const {data, isSuccess, refetch} = useGetRandomImageQuery?.()
    const [loginFun, {isLoading}] = useLoginMutation?.()
    const [getUserInfoFun] = useGetUserInfoMutation?.()

    // const [dd,setdd] = useState<string>('')

    useEffect(() => {
        // initWeChat()
        if (isSuccess) setCodeImg(data?.result)
        else setCodeImg('')
    }, [isSuccess, data])

    const getCodeImg = () => {
        refetch()
    }

    const handleLogin = () => {
        if (!agreement) {
            setIsShow(true)
            return
        }

        takeLogin()
    }

    const getUserInfo = () => {
        getUserInfoFun({}).then(res => {
            dispatch(set_userInfo(res.data?.result))
        })
    }

    // 初始化微信SDK
    // const initWeChat = async () => {
    //     try {
    //         await WeChat.registerAppAsync('wx10684715b8f3b501');
    //         console.log('微信SDK初始化成功');
    //     } catch (error) {
    //         console.error('初始化失败:', error);
    //     }
    // };

    // const login = async () => {
    //     try {
    //         const { type, code } = await WeChat.sendAuthRequestAsync({
    //             scope: 'snsapi_userinfo',
    //             state: 'expo_auth'
    //         });
    //
    //         if (type === 'success') {
    //             const params = new URLSearchParams({
    //                 appid: 'YOUR_WECHAT_APPID',
    //                 secret: 'YOUR_WECHAT_SECRET',
    //                 code,
    //                 grant_type: 'authorization_code'
    //             });
    //
    //             const response = await fetch(
    //                 `https://api.weixin.qq.com/sns/oauth2/access_token?${params}`
    //             );
    //
    //             const data = await response.json();
    //             console.log('Access Token:', data);
    //         }
    //     } catch (error) {
    //         console.error('微信登录失败:', error);
    //     }
    // };

    const openWebPage = async () => {
        await WebBrowser.openBrowserAsync('https://zhilingxing.com/privacy.html');
    };

    function takeLogin() {
        let params = {
            password: userPassword,
            username: userName,
            captcha: code,
            checkKey: 1629428467008
        }
        loginFun(params).then(({data: {code, result}}) => {
            refetch()
            console.log(data);
            if (code === 200) {
                dispatch(set_token(result?.token))
                dispatch(set_loginData(result))
                router.replace('/(tabs)')
                getUserInfo()
            }
        })
    }

    return (
        // <KeyboardAvoidingView behavior={Platform.OS == "ios" ? "padding" : "height"} style={styles.container}>
        //     {/*<StatusBar style='light'></StatusBar>*/}
        //     <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
        <View style={{flex: 1, width: '100%', height: '100%', backgroundColor: 'white',position: 'release'}}>
            <ImageBackground
                source={require('@/assets/images/login/login_bg.png')}
                style={{flex: 1, width: '100%', height: 350}}
                resizeMode='cover'
            >
                <View style={styles.wrapper}>
                    <Animated.Image
                        style={styles.logo}
                        resizeMode={'contain'}
                        source={require('@/assets/images/login/logo.png')}
                        entering={FadeInUp.delay(1200).duration(500)}
                    ></Animated.Image>
                    <Animated.Text style={styles.ad_txt}
                                   entering={FadeInLeft.delay(1200).duration(500)}>让AI营销更智能</Animated.Text>
                    <View style={styles.content}>
                        <Text style={styles.label}>用户名：</Text>
                        <FcTextInput
                            leftIconEle={
                                <Text style={styles.input_icon}>&#xe658;</Text>
                            }
                            text={userName} placeholder={'请输入用户名'}
                            onChangeText={setUserName}
                            style={styles.input}
                            inputStyle={styles.inputStyle}
                            height={48}/>
                        <Text style={styles.label}>密码：</Text>
                        <FcTextInput type='password' text={userPassword} placeholder={'请输入密码'}
                                     onChangeText={setUserPassword}
                                     style={styles.input}
                                     inputStyle={styles.inputStyle}
                                     height={48}/>
                        <Text style={styles.label}>验证码：</Text>
                        <FcTextInput
                            keyboardType={'number-pad'}
                            leftIconEle={
                                <Text style={[styles.input_icon, {fontSize: 18}]}>&#xe605;</Text>
                            }
                            positionEle={
                                <TouchableOpacity onPress={() => getCodeImg()}>
                                    <LinearGradient
                                        colors={['rgba(40, 86, 255, 0.1)', 'rgba(190, 70, 255, 0.25)']}
                                        start={{x: 0, y: 0}}
                                        end={{x: 1, y: 1}}
                                        style={styles.gradient}
                                    >

                                        {/*<Text>ddd</Text>*/}
                                        <Image style={styles.code} resizeMode={'contain'} source={{uri: codeImg}}></Image>
                                        {/*<Image style={styles.code} resizeMode={'contain'} source={{uri:dd}}></Image>*/}
                                    </LinearGradient>
                                </TouchableOpacity>
                            }
                            text={code} placeholder={'请输入验证码'}
                            onChangeText={setCode}
                            style={styles.input}
                            inputStyle={styles.inputStyle}
                            height={48}/>
                        <View style={styles.remember_psd}>
                            <TouchableOpacity style={styles.remember_psd} onPress={() => setRemember(!remember)}>
                                {remember &&
                                    <LinearGradient
                                        colors={['#6989FF', '#C65EFD']}
                                        start={{x: 0, y: 0}}
                                        end={{x: 1, y: 1}}
                                        style={styles.remember_psd_icon}
                                    >
                                        <Text style={[styles.input_icon, {color: 'white'}]}>&#xe64d;</Text>
                                    </LinearGradient>
                                }
                                {!remember && <View style={styles.select_box}></View>}
                                <Text style={styles.remember_psd_txt}>记住密码</Text>
                            </TouchableOpacity>
                        </View>
                        <FcButton
                            type='BjJB'
                            colors={['#6989FF', '#C65EFD']}
                            style={styles.login_btn}
                            itemStyle={styles.login_btn_txt}
                            textName='登录'
                            disable={!(userName && userPassword && code)}
                            onClick={() => handleLogin()}
                        />

                        <View style={styles.login_way}>
                            <Text style={styles.line}></Text>
                            <Text style={styles.login_way_txt}>其他登录方式</Text>
                            <Text style={styles.line}></Text>
                        </View>
                        {/*<WechatLogin />*/}
                        <Animated.View style={styles.login_btns_wrap} entering={FadeInDown.delay(1200).duration(500)}>
                            <TouchableOpacity style={styles.login_btns}>
                                <Image style={styles.login_btns_img}
                                       source={require('@/assets/images/login/login_icon1.png')}></Image>
                                <Text style={styles.login_btns_txt}>微信登录</Text>
                            </TouchableOpacity>
                            {/*<TouchableOpacity style={styles.login_btns}>*/}
                            {/*    <Image style={styles.login_btns_img}*/}
                            {/*           source={require('@/assets/images/login/login_icon2.png')}></Image>*/}
                            {/*    <Text style={styles.login_btns_txt}>企业微信登录</Text>*/}
                            {/*</TouchableOpacity>*/}
                        </Animated.View>
                        {/*<LoginTest></LoginTest>*/}
                        {/*<Text>{process.env.EXPO_PUBLIC_API_URL}</Text>*/}
                        {/*<Image style={{width:70,height: 48}} resizeMode={'contain'} source={{uri:dd}}></Image>*/}
                        {/*<Image style={{width:70,height: 48}} resizeMode={'contain'} source={{uri:codeImg}}></Image>*/}

                        <Animated.View style={styles.agreement_wrap} entering={FadeInDown.delay(1200).duration(500)}>
                            <TouchableOpacity style={styles.remember_psd} onPress={() => setAgreement(!agreement)}>
                                {agreement &&
                                    <LinearGradient
                                        colors={['#6989FF', '#C65EFD']}
                                        start={{x: 0, y: 0}}
                                        end={{x: 1, y: 1}}
                                        style={styles.agreement_icon}
                                    >
                                        <Text
                                            style={[styles.input_icon, {color: 'white', fontSize: 16}]}>&#xe64d;</Text>
                                    </LinearGradient>
                                }
                                {!agreement && <View style={styles.agreement_box}></View>}
                                <Text style={[styles.agreement_txt, {marginLeft: 8}]}>您已阅读并同意智灵星AI的</Text>
                            </TouchableOpacity>

                            <Text style={[styles.agreement_txt, {color: '#2856FF'}]}
                                  onPress={openWebPage}>《用户隐私协议》</Text>
                        </Animated.View>
                    </View>
                </View>



                <Modal
                    visible={isShow}
                    transparent={true}
                    onRequestClose={() => setIsShow(false)}

                >
                    <View style={styles.agreement_hint_wrap}>
                        <LinearGradient
                            colors={['#CACBFF', '#ffffff']}
                            start={{x: 1, y: 0}}
                            end={{x: 1, y: 1}}
                            style={styles.agreement_hint}
                        >
                            <Text style={styles.agree_title}>用户隐私协议</Text>
                            <View style={styles.agree_txt_wrap}>
                                <Text style={[styles.agree_txt]}>您已阅读并同意</Text>
                                <Text style={[styles.agree_txt, {color: '#2856FF'}]}
                                      onPress={openWebPage}>《用户隐私协议》</Text>
                            </View>
                                <View style={styles.btn_wrap}>
                                    <FcButton
                                        type='BjJB'
                                        colors={['#EDF1F6', '#EDF1F6']}
                                        style={{width: 96,height:40}}
                                        itemStyle={{fontsize: 14, color: '#8A8D8F',borderRadius:8}}
                                        textName='取消'
                                        onClick={() => setIsShow(false)}
                                    />
                                    <FcButton
                                        type='BjJB'
                                        colors={['#7E9AFF', '#C87AFD']}
                                        style={{width: 96,height:40,marginLeft: 7}}
                                        itemStyle={{fontsize: 14, color: '#FFFFFF',borderRadius:8}}
                                        textName='同意'
                                        onClick={() => {
                                            setIsShow(false)
                                            takeLogin()
                                        }}
                                    />
                                </View>
                        </LinearGradient>
                    </View>
                </Modal>
            </ImageBackground>
        </View>
        //     </TouchableWithoutFeedback>
        // </KeyboardAvoidingView>
    );
};

export default index;

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white'
    },
    wrapper: {
        flex: 1,
    },
    content: {
        backgroundColor: 'rgba(255,255,255,0.8)',
        borderRadius: 12,
        marginTop: 230,
        paddingHorizontal: 24,
        paddingVertical: 24,
        overflow: "hidden"
    },
    label: {
        lineHeight: 21,
        color: 'rgba(0,0,0,0.9)',
        fontSize: 15
    },
    input: {
        marginBottom: 16,
        marginTop: 8,
        fontSize: 15
    },
    inputStyle: {
        fontSize: 15,
        lineHeight: 20,
    },
    title: {
        color: Colors.white,
        fontSize: 24,
        fontWeight: '600',
        letterSpacing: 1.5,
        lineHeight: 36,
        textAlign: "center"
    },
    description: {
        color: Colors.white,
        fontSize: 16,
        fontWeight: '500',
        letterSpacing: 1.2,
        lineHeight: 22,
        textAlign: "center"
    },
    btn: {
        backgroundColor: Colors.tint,
        paddingVertical: 15,
        marginVertical: 20,
        alignItems: 'center',
        borderRadius: 10
    },
    btnText: {
        color: Colors.white,
        fontSize: 16,
        fontWeight: '700'
    },
    input_icon: {
        fontFamily: 'FcIconFont',
        fontSize: 20,
        color: 'rgba(0,0,0,0.5)'
    },
    gradient: {
        width: 88,
        height: 48,
        marginRight: -12,
        marginLeft: 10,
        display: 'flex',
        alignItems: "center",
        justifyContent: 'center',
        flexShrink: 0,
        // position: 'absolute',
        // right: 0,
        // top: 0,gradient
    },
    code: {
        width: 70,
        height: '100%',
    },
    remember_psd_icon: {
        width: 20,
        height: 20,
        borderRadius: 2,
        display: 'flex',
        alignItems: "center",
        justifyContent: 'center'
    },
    remember_psd: {
        display: 'flex',
        alignItems: "center",
        flexDirection: "row"
    },
    select_box: {
        width: 20,
        height: 20,
        borderRadius: 2,
        borderWidth: 0.5,
        borderColor: 'rgba(0, 0, 0, 0.3)'
    },
    remember_psd_txt: {
        marginLeft: 7,
        fontSize: 14,
        color: '#3D3D3D'
    },
    login_btn: {
        width: '100%',
        height: 48,
        marginTop: 16,
        marginBottom: 29,
    },
    login_btn_txt: {
        fontSize: 17,
        fontWeight: 'bold',
        color: 'white',
        borderRadius: 8
    },
    login_way: {
        display: 'flex',
        alignItems: "center",
        flexDirection: "row"
    },
    line: {
        flex: 1,
        height: 1,
        backgroundColor: '#E7EAF1'
    },
    login_way_txt: {
        fontSize: 12.5,
        color: '#9CA3AF',
        paddingHorizontal: 15
    },
    login_btns_wrap: {
        display: 'flex',
        alignItems: "center",
        justifyContent: "center",
        flexDirection: "row",
        marginTop: 22
    },
    login_btns: {
        display: 'flex',
        flexDirection: 'column',
        alignItems: "center",
        justifyContent: "center",
        marginHorizontal: 22
    },
    login_btns_img: {
        width: 42,
        height: 42,
        marginBottom: 7
    },
    login_btns_txt: {
        fontSize: 11,
        lineHeight: 14,
        color: '#4B5563'
    },
    logo: {
        width: 121,
        height: 35,
        position: 'absolute',
        top: 87,
        left: 32,
    },
    ad_txt: {
        position: 'absolute',
        top: 138,
        left: 32,
        fontSize: 21,
        color: '#3D3D3D',
        fontFamily: 'DingTalk JinBuTi'
    },
    agreement_wrap: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        // position: 'absolute',
        // bottom: 24,
        // left: 0,
        width: '100%',
        marginTop: 56,
    },
    agreement_icon: {
        width: 18,
        height: 18,
        borderRadius: 40,
        display: 'flex',
        alignItems: "center",
        justifyContent: 'center'
    },
    agreement_box: {
        width: 18,
        height: 18,
        borderRadius: 40,
        borderWidth: 0.5,
        borderColor: 'rgba(0, 0, 0, 0.3)',
    },
    agreement_txt: {
        fontSize: 12,
        lineHeight: 22,
        color: '#3D3D3D'
    },
    agreement_hint_wrap: {
        width: '100%',
        height: '100%',
        backgroundColor: 'rgba(0,0,0,0.6)',
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    agreement_hint: {
        width: 280,
        height: 180,
        borderRadius: 8,
        alignItems: 'center',
        justifyContent: 'center',
    },
    agree_title: {
        fontSize: 18,
        lineHeight: 26,
        color: 'rgba(0, 0, 0, 0.9)',
    },
    agree_txt_wrap: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 22,
    },
    agree_txt: {
        fontSize: 14,
        lineHeight: 26,
        color: 'rgba(0, 0, 0, 0.9)',
    },
    btn_wrap: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: 22,
    },
});
